package com.sakura.oj.service.impl;

import com.sakura.oj.common.ErrorCode;
import com.sakura.oj.common.UploadResult;
import com.sakura.oj.exception.BusinessException;
import com.sakura.oj.model.enums.AccessPolicyType;
import com.sakura.oj.service.OssService;
import com.sakura.oj.utils.OssClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * OSS 服务实现类
 */
@Slf4j
@Service
public class OssServiceImpl implements OssService {

    @Resource
    private OssClient storage;

    /**
     * 上传 MultipartFile 到对象存储服务
     *
     * @param file 要上传的 MultipartFile 对象
     * @return 上传成功后的返回可访问的URL信息
     */
    @Override
    public String upload(MultipartFile file) {
        String originalfileName = file.getOriginalFilename();
        String suffix = StringUtils.substring(originalfileName, originalfileName.lastIndexOf("."), originalfileName.length());

        UploadResult uploadResult;
        try {
            uploadResult = storage.uploadSuffix(file.getBytes(), suffix, file.getContentType());
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, e.getMessage());
        }
        return this.matchingUrl(uploadResult).getUrl();

    }

    /**
     * 桶类型为 private 的URL 修改为临时URL时长为120s
     *
     * @return oss 匹配Url的OSS对象
     */
    private UploadResult matchingUrl(UploadResult oss) {

        // 仅修改桶类型为 private 的URL，临时URL时长为120s
        if (AccessPolicyType.PRIVATE == storage.getAccessPolicy()) {
            oss.setUrl(storage.getPrivateUrl(oss.getFilename(), 120));
        }
        return oss;
    }
}
